package com.hqyj.finance.server.equity.financeequity.utils;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Resource(name = "customRedisTemplate")
    private RedisTemplate<String, Object> redisTemplate;   //redisTemplate

    /**
     * 往redis中缓存数据
     *
     * @param key
     * @param object
     * @return
     */
    public boolean set(String key, Object object) {
        ValueOperations<String, Object> vo = redisTemplate.opsForValue();
        vo.set(key, object);
        return true;
    }

    public boolean set(String key,Object object,long duration){
        ValueOperations<String, Object> vo = redisTemplate.opsForValue();
        //表示5分钟后自动过期
        vo.set(key, object,5, TimeUnit.MINUTES);
        return true;
    }

    /**
     * 根据key从redis服务器中获取value值
     *
     * @param key
     * @return
     */
    public Object get(String key) {
        ValueOperations<String, Object> vo = redisTemplate.opsForValue();
        return vo.get(key);
    }

    public boolean hasKey(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    /**
     * 根据key从Redis中删除value值
     */
    public void remove(String key) {
        redisTemplate.delete(key);
    }

    /*
    * 根据前缀模糊删除key的集合
    * */

    public void removeByPrex(String prex) {
        Set<String> keys = redisTemplate.keys(prex+"*");
        if (CollectionUtils.isNotEmpty(keys)) {
            redisTemplate.delete(keys);
        }
    }
}

